import 'dart:convert';

import 'package:inmotion_pro/custom_exception/lx_exception.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mixin/bluetooth_mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/pages/protocol_business/base/base_business.dart';
import 'package:inmotion_pro/pages/mixin/protocol_mixin.dart';
import 'package:inmotion_pro/pages/mixin/vehicle_type_mixin.dart';
import 'package:inmotion_pro/pages/models/product_info_model.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:inmotion_pro/service/log_service.dart';
import 'package:inmotion_pro/service/realtime_data_server/realtime_data_service.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/foundation.dart';

import '../../../service/cache_config_service.dart';

// Lorin业务类
class LorinBusiness extends BaseBusiness
    with CacheMixin, BluetoothMixin, VehicleTypeMixin, ProtocolMixin {
  @override
  Future<bool> vehicleBluetoothConnectSuccess(
    CustomScanResult scanResult,
  ) {
    if (!GlobalService.to.isIntegratedInfoAvailable) {
      return protocolMixinGetSn().then((sn) {
        if (sn.isNotEmpty) {
          LogService.to.info("【$runtimeType】设备SN: $sn");
          return protocolMixinGetProductModel().then((productModel) async {
            if (productModel.isNotEmpty) {
              LogService.to.info("【$runtimeType】产品型号: $productModel");
              return protocolMixinGetFirmwareVersion().then((firmwareInfoList) {
                if (firmwareInfoList.isNotEmpty) {
                  LogService.to.info(
                    "【$runtimeType】固件信息: ${firmwareInfoList.map((e) => e.toMap())}",
                  );
                  // 将产品型号、固件信息写入缓存
                  return cacheMixinUpdateCacheVehicle(
                    scanResult.device.advName,
                    sn: sn,
                    productModel: productModel,
                    firmwareInfo: jsonEncode(
                        firmwareInfoList.map((e) => e.toMap()).toList()),
                  );
                }
                throw LxException(local.get_vehicle_firmware_version_failed);
              });
            }
            throw LxException(local.get_vehicle_product_info_failed);
          });
        }
        throw LxException(local.get_vehicle_sn_failed);
      });
    } else {
      // 当综合产品信息已存在时，可直接走综合产品信息获取API
      return bluetoothHelperGetIntegratedProductInfo().then((productInfo) {
        LogService.to.info("【$runtimeType】产品信息: $productInfo");
        ProductInfoModel productInfoModel =
            ProductInfoModel.fromMap(productInfo);
        return cacheMixinUpdateCacheVehicle(
          scanResult.device.advName,
          sn: productInfoModel.sn,
          productModel: productInfoModel.productModel,
          firmwareInfo: jsonEncode(productInfoModel.firmwareInfoList
              .map((item) => item.toMap())
              .toList()),
        );
      });
    }
  }

  @override
  Future<bool> startLoopToGetVehicleRealTimeData({
    required List<(PollingTimerType, int)> pollingTypes,
  }) {
    if (GlobalService.to.isSupportRealtimePush()) {
      debugPrint("✅✅✅ 开启周期性数据上报");
      return RealTimeDataService.to.addListener();
    } else {
      debugPrint("✅✅✅【$runtimeType】开始循环获取车辆实时数据");
      if (GlobalService.to.isIntegratedInfoAvailable) {
        // 如果版本支持，则需要删除掉单独的实时数据轮询
        pollingTypes.removeWhere((element) =>
            element.$1 == PollingTimerType.realtimeAll ||
            element.$1 == PollingTimerType.realtimeInfo ||
            element.$1 == PollingTimerType.realtimeStatus ||
            element.$1 == PollingTimerType.realtimeError);
      } else {
        // 如果版本不支持，则移除综合实时全部信息的轮询
        pollingTypes.removeWhere(
            (element) => element.$1 == PollingTimerType.integratedRealtimeAll);
      }
      return RealTimeDataService.to.startLoop(pollingTypes);
    }
  }

  @override
  Future<bool> stopLoopToGetVehicleRealTimeData() {
    if (GlobalService.to.isSupportRealtimePush()) {
      debugPrint("⏸️ 停止周期性数据上报");
      return RealTimeDataService.to.removeListener();
    } else {
      debugPrint("⏸️ 停止循环获取车辆实时数据");
      return RealTimeDataService.to.stopLoop();
    }
  }

  @override
  Future<bool> buildSafeConnection() {
    return protocolMixinBuildSafeConnection().then((success) {
      if (success) {
        LogService.to.info("✅ 建立安全连接成功");
        return CacheConfigService.to.setSecureConnection(true);
      } else {
        LogService.to.error("❌ 建立安全连接失败");
        return CacheConfigService.to
            .setSecureConnection(false)
            .then((value) => false);
      }
    });
  }
}
